<template>
  <div class="study-room-container">
    <!-- 标题区域 -->
    <div class="page-title">
      <h2>你の自习室 - 网格布局编辑器</h2>
      <!-- 底部统计信息 -->
      <div class="statistics" v-if="gridData.length">
        <el-descriptions column="4" border size="small">
          <el-descriptions-item label="总格子数">{{ gridData.length }}</el-descriptions-item>
          <el-descriptions-item label="座位数">{{ countType('座位') }}</el-descriptions-item>
          <el-descriptions-item label="非座位数">{{ countType('非座位') }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <!-- 网格容器（居中显示） -->
    <div class="grid-center-container">
      <div
          class="grid-wrapper"
          :style="{
          gridTemplateColumns: `repeat(${maxX}, ${cellSize}px)`,
          gap: '2px'
        }"
          v-loading="loading"
          element-loading-text="加载布局中..."
      >
        <!-- 循环渲染网格单元格 -->
        <div
            v-for="cell in sortedGridData"
            :key="cell.id"
            class="grid-cell"
            :style="{
            width: `${cellSize}px`,
            height: `${cellSize}px`,
            backgroundColor: cell.photo ? 'transparent' : '#f5f5f5'
          }"
            @click="handleCellClick(cell)"
        >
          <!-- 只显示有图片的元素 -->
          <el-image
              v-if="cell.photo"
              :src="cell.photo"

              fit="cover"
              class="cell-image"
          ></el-image>
        </div>
      </div>
    </div>



    <!-- 编辑对话框 -->
    <el-dialog
        title="编辑格子信息"
        :visible.sync="editDialogVisible"
        width="400px"
    >
      <el-form :model="currentEditCell" label-width="100px">
        <el-form-item label="横坐标">
          <el-input v-model="currentEditCell.x" disabled></el-input>
        </el-form-item>
        <el-form-item label="纵坐标">
          <el-input v-model="currentEditCell.y" disabled></el-input>
        </el-form-item>
        <el-form-item label="元素类型" prop="typeId">
          <el-select
              v-model="currentEditCell.typeId"
              placeholder="请选择元素类型"
              style="width: 100%"
          >
            <el-option
                v-for="type in gridTypes"
                :key="type.id"
                :label="type.name"
                :value="type.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="元素名称">
          <el-input v-model="currentEditCell.name" disabled></el-input>
        </el-form-item>
        <el-form-item label="是否为座位">
          <el-input v-model="currentEditCell.type" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Home',
  data() {
    return {
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      gridData: [],               // 网格数据
      sortedGridData: [],         // 排序后的网格数据
      gridTypes: [],              // 元素类型列表
      maxX: 0,                    // 最大X坐标
      maxY: 0,                    // 最大Y坐标
      cellSize: 70,               // 单元格大小
      loading: false,             // 加载状态
      editDialogVisible: false,   // 编辑对话框显示状态
      currentEditCell: {}         // 当前编辑的单元格
    }
  },
  created() {
    // 初始化加载数据
    this.loadAllData();
  },
  methods: {
    // 加载所有数据
    loadAllData() {
      this.loading = true;
      // 并行加载网格数据和元素类型数据
      Promise.all([
        this.$request.get('/grid/selectAll'),
        this.$request.get('/gridType/selectAll')
      ])
          .then(([gridRes, typeRes]) => {
            // 处理网格数据
            if (gridRes.code === '200' && Array.isArray(gridRes.data)) {
              this.gridData = gridRes.data;
              this.processGridData();
            } else {
              this.$message.error('获取网格数据失败');
            }

            // 处理元素类型数据
            if (typeRes.code === '200' && Array.isArray(typeRes.data)) {
              this.gridTypes = typeRes.data;
            }
          })
          .catch(error => {

          })
          .finally(() => {
            this.loading = false;
          });
    },

    // 处理网格数据
    processGridData() {
      if (!this.gridData.length) return;

      // 计算最大坐标值
      this.maxX = Math.max(...this.gridData.map(item => item.x));
      this.maxY = Math.max(...this.gridData.map(item => item.y));

      // 排序：按Y升序，再按X升序
      this.sortedGridData = [...this.gridData].sort((a, b) => {
        if (a.y !== b.y) return a.y - b.y;
        return a.x - b.x;
      });
    },

    // 点击单元格
    handleCellClick(cell) {
      // 深拷贝单元格数据，避免直接修改原数据
      this.currentEditCell = JSON.parse(JSON.stringify(cell));
      this.editDialogVisible = true;
    },

    // 保存编辑
    saveEdit() {
      // 查找对应的类型信息，补充名称和图片等信息
      const typeInfo = this.gridTypes.find(type => type.id === this.currentEditCell.typeId);
      if (typeInfo) {
        this.currentEditCell.name = typeInfo.name;
        this.currentEditCell.type = typeInfo.type;
        this.currentEditCell.photo = typeInfo.photo;
      }

      // 调用更新接口
      this.$request({
        url: '/grid/update',
        method: 'PUT',
        data: this.currentEditCell
      }).then(res => {
        if (res.code === '200') {
          this.$message.success('更新成功');
          // 关闭对话框并重新加载数据
          this.editDialogVisible = false;
          this.loadAllData();
        } else {
          this.$message.error(res.msg || '更新失败');
        }
      }).catch(() => {
        this.$message.error('网络异常，更新失败');
      });
    },

    // 统计指定类型的数量
    countType(type) {
      return this.gridData.filter(item => item.type === type).length;
    }
  }
}
</script>

<style scoped>
.study-room-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.page-title {
  text-align: center;
  margin-bottom: 5px;
}

.page-title h2 {
  margin: 0;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

/* 居中容器 */
.grid-center-container {
  display: flex;
  justify-content: center;
  margin-bottom: 30px;
  overflow-x: auto;
  padding: 0 10px;
}

/* 网格容器 */
.grid-wrapper {
  display: grid;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
}

/* 网格单元格 */
.grid-cell {
  border: 1px solid #eee;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.grid-cell:hover {
  transform: scale(1.05);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 10;
}

.cell-image {
  width: 100%;
  height: 100%;
  border-radius: 3px;
}

/* 统计信息区域 */
.statistics {
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.08);
  max-width: 800px;
  margin: 0 auto;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .cellSize {
    max-width: 50px;
  }

  .statistics .el-descriptions {
    column-count: 2;
  }
}
</style>
